/**
 * 导出表格数据到 Excel 文件
 * @param {Array} tableData - 表格数据
 * @param {Array} fieldLabels - 表头组成的数组
 * @param {Array} fieldKeys - 列属性名组成的数组
 * @param {String} fileName - 导出的文件名
 */
function exportExcel(tableData, fieldLabels, fieldKeys, fileName) {
  let dataStr = fieldLabels.toString() + '\r\n';
  tableData.forEach(item => {
    fieldKeys.forEach(key => {
      // 加引号是为了使换行符在单元格内正常显示
      dataStr += `"    ${item[key]}    "\t,`;
    });
    dataStr += '\r\n';
  });

  // encodeURIComponent 解决中文乱码
  const url = "data:text/xls;charset=utf-8,\ufeff" + encodeURIComponent(dataStr);
  const link = document.createElement("a");
  link.href = url;
  link.download = fileName + ".xls";
  link.style.display = 'none';
  document.body.appendChild(link);
  link.click();
  document.body.removeChild(link); //释放标签
}

function downloadExcelBlob(data, fileName) {
  let blob = new Blob([data], {
    type: "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet; charset=utf-8",
  });
  let filename = fileName || "导出数据";
  // 将blob对象转为一个URL
  var blobURL = window.URL.createObjectURL(blob);
  // 创建一个a标签
  var tempLink = document.createElement("a");
  // 隐藏a标签
  tempLink.style.display = "none";
  // 设置a标签的href属性为blob对象转化的URL
  tempLink.href = blobURL;
  // 给a标签添加下载属性
  tempLink.setAttribute("download", filename);
  if (typeof tempLink.download === "undefined") {
    tempLink.setAttribute("target", "_blank");
  }
  // 将a标签添加到body当中
  document.body.appendChild(tempLink);
  // 启动下载
  tempLink.click();
  // 下载完毕删除a标签
  document.body.removeChild(tempLink);
  window.URL.revokeObjectURL(blobURL);
}

const debounce = (callback, wait) => {
  let timer = null
  const debounced = () => {
    clearTimeout(timer)
    timer = setTimeout(callback, wait)
  }
  debounced.cancel = () => {
    clearTimeout(timer)
  }
  return debounced
}

function getRandomCode() {
  let code = '';
  for (let i = 0; i < 6; i++) {
    code += parseInt(Math.random() * 10);
  }
  return code;
}

// 表格自适应工具函数
export const calculateTableHeight = () => {
  // 获取视窗高度
  const viewportHeight = window.innerHeight;
  
  // 计算表格可用高度
  // 减去页面头部、导航栏、搜索区域、按钮区域、分页区域等的高度
  const headerHeight = 86; // 页面头部高度
  const searchHeight = 60; // 搜索区域高度
  const buttonHeight = 50; // 按钮区域高度
  const paginationHeight = 56; // 分页区域高度
  const padding = 40; // 各种内边距
  
  const availableHeight = viewportHeight - headerHeight - searchHeight - buttonHeight - paginationHeight - padding;
  
  // 设置最小高度为 300px，确保在小屏幕上也有合理的显示效果
  const minHeight = 300;
  const calculatedHeight = Math.max(availableHeight, minHeight);
  
  return `${calculatedHeight}px`;
};

// 表格自适应混入
export const tableMixin = {
  data() {
    return {
      tableMaxHeight: 'calc(100vh - 250px)',
    };
  },
  mounted() {
    this.calculateTableHeight();
    window.addEventListener('resize', this.calculateTableHeight);
  },
  beforeUnmount() {
    window.removeEventListener('resize', this.calculateTableHeight);
  },
  methods: {
    calculateTableHeight() {
      this.tableMaxHeight = calculateTableHeight();
    },
  },
};

export {
  exportExcel,
  downloadExcelBlob,
  debounce,
  getRandomCode,
}
